﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using HtmlAgilityPack;

namespace ProductCollector {
    public class EasyBreatheSearcher : ISiteSearcher
    {
        private const string SEARCH_URL =
            "http://www.easybreathe.com/cart.php?search={0}&m=search_results&pageNumber={1}";

        private const string HOME_URL = "http://www.easybreathe.com";
        public IList<Product> Search(SearchCriteria criteria) {
            var web = new HtmlWeb();
            string url = string.Format(SEARCH_URL, criteria.SearchValue, criteria.CurrentPageIndex);
            List<Product> result = new List<Product>();

            HtmlDocument doc = web.Load(url);
            var gridNode = doc.DocumentNode.SelectSingleNode("//ul[@id='products_ul']");
            if(gridNode == null)
            {
                return result;
            }
            var allProds = gridNode.SelectNodes("./li");

            foreach (HtmlNode node in allProds) {
                Product p = GetProductByNode(node);
                if (p != null) {
                    result.Add(p);
                }
                if (result.Count >= criteria.NumOfProduct) {
                    break;
                }
            }
            return result;
        }
        private Product GetProductByNode(HtmlNode liNode) {
            Product p = new Product();
            var link = liNode.SelectSingleNode("./div[contains(@class,'left')]/div[contains(@class,'img')]/a");
            if (link != null)
            {
                p.OriginalUrl = link.GetAttributeValue("href", HOME_URL);
                var img = link.SelectSingleNode("./img");
                if(img != null)
                {
                    p.ThumbImg = img.GetAttributeValue("src", HOME_URL);
                }

            }
            var title = liNode.SelectSingleNode("./div[contains(@class,'right')]/div/a");
            if (title != null) {
                p.ProductName = title.InnerText;
            }
            var man = liNode.SelectSingleNode("./div[contains(@class,'right')]/div/p");
            if(man != null)
            {
                p.Manufacturer = man.InnerText;
            }

            var price = liNode.SelectSingleNode("./div[contains(@class,'right')]/span");
            if (price != null) {
                p.FormattedPrice = price.InnerText;
            }
            return p;
        }
        public int CountProduct(SearchCriteria criteria) {
            throw new NotImplementedException();
        }
    }
}
